﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.SessionState;

namespace DrillingTrack3D.controller
{
    /// <summary>
    /// Ajax 的摘要说明
    /// </summary>
    public partial class Ajax : IHttpHandler
    {
        protected HttpRequest Request;
        protected HttpResponse Response;
        protected HttpServerUtility Server;
        protected HttpSessionState Session;
        protected String ContentType;
        protected static String OutputString;   //必须为static    

        public Ajax()
        {
            Request = HttpContext.Current.Request;
            Response = HttpContext.Current.Response;
            Server = HttpContext.Current.Server;
            Session = HttpContext.Current.Session;
//            ContentType = "application/json";
            ContentType = "text/plain";
            if (!String.IsNullOrEmpty(Request["ContentType"]))
            {
                ContentType = Request["ContentType"].Replace("_", "/");
            }
            OutputString = "{\"error\":\"1\",\"message\":\"没改变OutputString初始值.\"}";  
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                String methodName = Request["cmd"];
                Type type = this.GetType();

                MethodInfo method = type.GetMethod(methodName);

                if (null != method)
                {
                    method.Invoke(this, null);
                }
            }
            catch (Exception ex)
            {
                OutputString = "{\"error\":\"1\",\"message\":\"" + ex.Message + "\"}";
                if (ex.InnerException != null)
                {
                    OutputString = "{\"error\":\"1\",\"message\":\"" + ex.Message + "\",\"InnerException\":\"" + ex.InnerException.Message + "\"}";
                }
            }
            
            Response.ContentType = ContentType;

            //输出结果    
            if (!string.IsNullOrEmpty(OutputString))
            {
                Response.Write(OutputString);
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}